﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;

namespace UserGroupData
{
    public class MemberRepository : IMemberRepository
    {
        public MemberDTO GetMember(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                var meeting = ctx.Members.Where(d => d.Id == id);
                var entity = meeting.FirstOrDefault();
                Mapper.CreateMap<Member, MemberDTO>();
                var dto = Mapper.Map<Member, MemberDTO>(entity);
                return dto;
            }
        }

        public List<MemberDTO> GetAllMembers()
        {
            using (var ctx = new UserGroupEntities())
            {
                var entities = ctx.Members.ToList();
                Mapper.CreateMap<Member, MemberDTO>();
                var dto = Mapper.Map<List<Member>, List<MemberDTO>>(entities);
                return dto;
            }
        }

        public int AddNewMember(MemberDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<MemberDTO, Member>();
                var entity = Mapper.Map<MemberDTO, Member>(dto);
                ctx.AddToMembers(entity);
                ctx.SaveChanges();
                return entity.Id;

            }
        }

        public void UpdateMember(MemberDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<MemberDTO, Member>();
                var entity = Mapper.Map<MemberDTO, Member>(dto);
                ctx.ApplyCurrentValues("Members", entity);
                ctx.SaveChanges();
            }
        }

        public void DeleteMemberDTO(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                Member dbDept = ctx.Members.First(d => d.Id == id);
                ctx.DeleteObject(dbDept);
                ctx.SaveChanges();
            }
        }

    }
}
